<template>
    <div id="ActiveEdit" :class="`router-box info-con${readOnly ? ' readOnly' : ''}`" pageName="活动管理 > 查看/新建/编辑">
        <el-form ref="activeForm" :model="activeInfo" :rules="rules" label-width="8rem" label-suffix="：">
            <div style="font-weight: 600;">活动信息</div>
            <div style="display: flex;">
                <el-form-item label="活动主题" prop="title">
                    <el-input v-model="activeInfo.title" size="small" maxlength="20" :readonly="readOnly"
                        :clearable="!readOnly" :placeholder="readOnly ? '' : '请输入'" style="width: 20rem;"></el-input>
                </el-form-item>

                <el-form-item label="活动日期" prop="startDate">
                    <el-date-picker v-model="activeInfo.startDate" size="small" value-format="yyyy-MM-dd"
                        :prefix-icon="readOnly ? ' ' : ''" :readonly="readOnly" :clearable="!readOnly" type="date"
                        :placeholder="readOnly ? '' : '请选择'" style="width: 15rem;"></el-date-picker>
                </el-form-item>
            </div>

            <div style="display: flex;">
                <el-form-item label="活动地点" prop="place">
                    <el-select v-model="activeInfo.place" size="small" maxlength="10" :disabled="readOnly"
                        :clearable="!readOnly" :placeholder="readOnly ? '' : '请输入'" style="width: 20rem;">
                        <el-option v-for="item in addressList" :label="item.name" :value="item.id" :key="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="更新人" prop="createUser">
                    <el-input v-model="activeInfo.createUser" size="small" maxlength="10" :readonly="readOnly"
                        :clearable="!readOnly" :placeholder="readOnly ? '' : '请输入'" style="width: 15rem;"></el-input>
                </el-form-item>
            </div>

            <el-form-item label="内容描述" prop="activityIntro">
                <el-input v-model="activeInfo.activityIntro" size="small" maxlength="200" type="textarea"
                    :autosize="{ minRows: readOnly ? 0 : 5 }" :readonly="readOnly" :clearable="!readOnly"
                    :placeholder="readOnly ? '' : '请输入'" style="width: 40rem;"></el-input>
            </el-form-item>

            <div style="font-weight: 600;">活动附件</div>
            <el-form-item label="上传照片" prop="activeDesc">
                <div class="limit-max" v-if="readOnly ? imageList.length : true">
                    <cf-upload width="8.56rem" height="8.06rem" :max="9" :readOnly="readOnly" :hideTips="true"
                        :list="imageList" @getFileList="getImgList"></cf-upload>
                </div>
            </el-form-item>

            <!-- <el-form-item prop="image" label="图片附件上传">
            <el-upload
                ref="uploadImage"
                :action="uploadAction"
                :beforeUpload="beforeUploadPicture"
                :on-change="imageChange"
                list-type="picture-card"
                name="files"
                :limit="3"
                multiple
                :auto-upload="false"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemovePicture">
                <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
            </el-form-item> -->

            <!-- <el-form-item label="上传照片" prop="file">
                <el-upload v-if="!readOnly" class="upload" action="#" :file-list="imageList"
                
                 :disabled="imageList.length > 8"
                    :show-file-list="false" :auto-upload="false" :on-change="uploadSuccess2" :before-remove="beforeRemove2"
                    :limit="9">
                    <el-button size="small" type="primary" :disabled="imageList.length > 8">上传附件</el-button>
                </el-upload>
                <ul v-if="imageList.length">
                    <li class="close-box" v-for="(file2, i) in imageList" :key="`imageList${i}`">
                        <span class="cursorPointer download" :title="file2.name" @click="downloadFile2(file2)">{{ file2.name
                        }}</span>
                        <span v-if="!readOnly" @click="beforeRemove2(file2, i)" class="remove-i"><i
                                class="el-icon-close"></i></span>
                    </li>
                </ul>
            </el-form-item> -->

            <!-- <el-form-item label="上传附件" prop="activeDesc">
                <div class="limit-max" v-if="readOnly ? imageList.length : true">
                    <cf-upload width="8.56rem" height="8.06rem" :max="9" :readOnly="readOnly" :hideTips="true" :list="imageList" @getFileList="getImgList1" type="file"></cf-upload>
                </div>
            </el-form-item> -->


            <el-form-item label="上传附件" prop="file">
                <el-upload v-if="!readOnly" class="upload" action="#" :file-list="fileList" :disabled="fileList.length > 0"
                    :show-file-list="false" :auto-upload="false" :on-change="uploadSuccess" :before-remove="beforeRemove"
                    :limit="1">
                    <el-button size="small" type="primary" :disabled="fileList.length > 0">上传附件</el-button>
                </el-upload>
                <ul v-if="fileList.length">
                    <li class="close-box" v-for="(file, i) in fileList" :key="`fileList${i}`">
                        <span class="cursorPointer download" :title="file.name" @click="downloadFile(file)">{{ file.name
                        }}</span>
                        <span v-if="!readOnly" @click="beforeRemove(file, i)" class="remove-i"><i
                                class="el-icon-close"></i></span>
                    </li>
                </ul>
            </el-form-item>

        </el-form>
        <form-submit :submit="submitText" :loading="loading" :cancel="cancelText"
            @handleSubmit="handleSubmit"></form-submit>

    </div>
</template>
<script>
import FormSubmit from "@/components/commonView/FormSubmit"
import CfUpload from "@/components/common/CFpcUpload"
export default {
    name: "ActiveManageEdit",
    components: { FormSubmit, CfUpload },
    data() {
        return {
    //         dialogImageUrl: '',
    //   dialogVisible: false,
    //   images:[],
    //   uploadAction: '',

            pageType: "", // 页面分类  0 新建  1 编辑  2 查看详情
            readOnly: false, // 是否只读，即是否是查看
            submitText: "", // 提交按钮文字，页面不同显示不同文字
            cancelText: "", // 取消按钮文字
            activeId: "", // 编辑/查看时的知识id
            activeInfo: {
                title: "", // 活动主题
                startDate: "", // 活动日期
                place: '', // 活动地点
                // placeName: '',
                createUser: '', // 更新人

                activityIntro: "", // 活动描述
                imgList: [], // 上传照片
                // pdfList: [], // 上传附件
                file: []
            },
            pageData: {
                // 分页数据
                pageNum: 1,
                pageSize: 10,
                total: 0,
            },
            rules: {
                // title: [{ required: true, validator: (rule, value, callback) => {const tips = this.tools.validateAnyStr(value, "活动主题", 2); callback(tips)}, trigger: 'blur' }],
                // startDate: [{ required: true, message: '请选择活动日期', trigger: 'blur' }],

                // placeName: [{ required: true, validator: (rule, value, callback) => {const tips = this.tools.validateAnyStr(value, "活动地点", 2); callback(tips)}, trigger: 'change' }],

                // createUser: [{ required: true, validator: (rule, value, callback) => {const tips = this.tools.validateAnyStr(value, "更新人姓名", 2); callback(tips)}, trigger: 'blur' }],

                // file: [
                //     { required: true, message: "请上传附件", trigger: "change" },
                // ],
            },
            addressList: [
                // { name: "一号会议室", id: "1", key: "1acd" },
                // { name: "户外", id: "2", key: "age4" },
            ],
            imageList: [], // 图片列表
            fileList: [], // 附件列表
            loading: false, // 按钮状态
        }
    },
    created() {
        // const form = this.$route.query
        // console.log('fff', form);
        // this.activeInfo = {...form}
    },
    watch: {
        $route: {
            handler(to) {
                this.activeId = to.query.id;
                this.pageType = to.query.pageType;
                this.readOnly = this.pageType === "2";
                this.submitText = this.readOnly ? "0" : this.pageType === "1" ? "保 存" : undefined;
                this.cancelText = this.readOnly ? "返回列表" : undefined;
                this.getActiveInfo();
            },
            immediate: true,
        }
    },
    created() {
        this.getBaseInfo();
    },
    methods: {
        // beforeUploadPicture(file){
            // const isImage = file.type == 'image/png' || file.type == 'image/jpg' ||  file.type == 'image/jpeg' || file.type == 'image/bmp' || file.type == 'image/gif' || file.type == 'image/webp';
            // const isLt2M = file.size <  1024 * 1024 * 2;
            // if (!isImage) {
            //     this.$message.error('上传只能是png,jpg,jpeg,bmp,gif,webp格式!');
            // }
            // if (!isLt2M) {
            //     this.$message.error('上传图片大小不能超过 2MB!');
            // }
            // return isImage && isLt2M;
        // },
        // handlePictureCardPreview(file) {
        //     this.dialogImageUrl = file.url;
        //     this.dialogVisible = true;
        // },
        // handleRemovePicture(file, fileList) {
        //     console.log(file, fileList);
        // },
        // imageChange(file, fileList, name) {
        //     console.log('imageChange',file, fileList, name);
        //     console.log(file, fileList);
        //     this.imageList = fileList;
        //     this.images['images'] = fileList;
        //     console.log('sss', this.images['images']);
        // },









        // 获取活动地点下拉菜单
        getBaseInfo() {
            let param = {
                pageNum: this.pageData.pageNum,
                pageSize: this.pageData.pageSize,
                parentId: this.$encryptByDES('801'),
                type: '201'
            }
            this.$request.get('/basicData/pagedQuery', param, res => {
                console.log('sswwq', res);
                this.addressList = res.list
                // this.tableData = res.list
                // this.pageData.total = res.total
            })
        },
        getActiveInfo() {
            if (this.pageType === "0") return
            let param = {
                id: this.activeId,
            }
            // /newActivity/query
            this.$request.get("/newActivity/query", param, res => {
                // console.log(res);
                // this.activeInfo.name = res.name;
                // this.activeInfo.startDate = res.startDate;
                // this.activeInfo.activityIntro = res.activityIntro;

                console.log('详情12', res);
                // this.activeInfo = {...res}
                // return
                this.activeInfo.title = res.title;
                this.activeInfo.startDate = res.startDate;
                this.activeInfo.place = res.place
                // this.activeInfo.placeName = res.placeName
                this.activeInfo.createUser = res.createUser
                this.activeInfo.activityIntro = res.activityIntro;
                // return

                // this.imageList = res.imgList;
                // this.fileList = this.tools.deepCopy([], res.pdfList);
                // this.activeInfo.file = this.tools.deepCopy([], res.pdfList);

                // this.imageList = this.tools.deepCopy([], res.imgList)
                this.fileList = this.tools.deepCopy([], res.annexList);
                // this.activeInfo.file = this.tools.deepCopy([], res.annexList);
            })
        },
        // uploadSuccess2(file, fileList){
        //     console.log('照片', file, fileList);
        //     this.imageList = fileList
        //     this.activeInfo.imgList = fileList
        //     this.$refs.activeForm.validateField('imgList')
        // },
        // beforeRemove2(file, index) {
        //     console.log('beforeRemove2图片', file, index, this.fileList);
        //     let param = {
        //         id: index
        //     }
        //     // this.$set(this.activeInfo, "file", "");
        //     // this.fileList = [];
        //     this.$set(this.activeInfo, "file", "");
        //     this.fileList.splice(index, 1)
        //     this.$refs.activeForm.validateField("file");

        //     // return
        //     this.$request.delete('/sysAnnex/delete', param, res => {
        //         // this.fileList.splice(index, 1)
        //         // this.$set(this.activeInfo, "file", "");
        //         this.fileList = [];
        //         // this.$refs.activeForm.validateField("file");
        //     })
        // },

        // 附件上传
        uploadSuccess(file, fileList) {
            console.log(file, fileList);
            // return
            // this.$set(this.activeInfo, 'file', fileList.length && !!file ? file.raw : "")
            this.fileList = fileList;
            this.activeInfo.file = fileList;

            // let pdfList = [];
            // this.fileList.map(data => {
            //     pdfList.push(data.raw);
            // })
            // this.activeInfo.file = pdfList;

            this.$refs.activeForm.validateField('file')
        },
        // beforeRemove(file, index) {
        //     console.log('beforeRemove', file, index);

            
        //     this.$set(this.activeInfo, "file", "");
        //     this.fileList = [];
        //     // this.fileList.splice(index, 1);
        //     // this.activeInfo.file.splice(index, 1);

        //     this.$refs.activeForm.validateField("file");
        // },

        beforeRemove(file, index) {
            console.log('beforeRemove', file, index, this.fileList);
            let param = {
                id: file.id
            }
            // this.$set(this.activeInfo, "file", "");
            // this.fileList = [];
            this.$set(this.activeInfo, "file", "");
            this.fileList.splice(index, 1)
            this.$refs.activeForm.validateField("file");

            // return
            this.$request.delete('/sysAnnex/delete', param, res => {
                // this.fileList.splice(index, 1)
                // this.$set(this.activeInfo, "file", "");
                this.fileList = [];
                // this.$refs.activeForm.validateField("file");
            })

            return


            this.$set(this.activeInfo, "file", "");
            this.fileList = [];
            // this.fileList.splice(index, 1);
            // this.activeInfo.file.splice(index, 1);

            this.$refs.activeForm.validateField("file");
        },



        // // 上传附件
        // uploadSuccess(file, fileList) {
        //     this.fileList = fileList;
        //     let pdfList = [];
        //     this.fileList.map(data => {
        //         pdfList.push(data.raw);
        //     })
        //     this.activeInfo.file = pdfList;
        //     console.log('this.activeInfo.file', this.activeInfo);
        // },
        // beforeRemove(file, index) {
        //     this.fileList.splice(index, 1);
        //     this.activeInfo.file.splice(index, 1);
        // },


        handleExceed() { },
        // /* 获取图片列表 */
        getImgList(list, fileList) {
            console.log('listAA', list, fileList);
            // this.$set(this.activeInfo, 'imageList', list.length && !!list ? list.raw : "")

            this.imageList = list;
            this.activeInfo.imgList = list
        },
        // getImgList1(list) {
        //     console.log('ass', list);
        // },


        // /* 获取图片列表 */
        // getImgList(list) {
        //     console.log('listAA',list);
        //     this.imageList = list;
        //     // for(let i = 0; i < this.imageList.length; i++){
        //     //     const img = this.imageList[i];
        //     //     console.log("图片文件：", img);
        //     // }

        // },
        /* 提交表单 */
        handleSubmit() {
            console.log('this.activeInfo', this.activeInfo);
            console.log('this.imageList', this.imageList);
            console.log('this.activeInfo.file', this.activeInfo.file);
            // return
            this.$refs.activeForm.validate((valid) => {
                if (valid) {

                    // console.log('asa1111111', this.activeInfo);
                    this.loading = true
                    const _that = this;
                    uploadImg();
                    async function uploadImg() {
                        // 传图片
                        // for (let i = 0; i < _that.imageList.length; i++) {
                        //     const img = _that.imageList[i];
                        //     console.log("图片文件：", img);
                        //     if(!img.raw) { // 是回显时的链接，直接跳过
                        //         _that.activeInfo.imgList.push({url: img.url, name: img.name});
                        //         continue;
                        //     }
                        //     let tips = true;
                        //     await _that.addFile("1", img, i).then(res => {
                        //         const filePre = img.name.split(".")[0].slice(0, 90);
                        //         const fileName = filePre + "." + img.name.split(".")[1];
                        //         _that.activeInfo.imgList.push({url: res.url, name: fileName});
                        //     }).catch(err => {
                        //         _that.activeInfo.imgList = [];
                        //         tips = false;
                        //     });
                        //     if(!tips) {
                        //         _that.loading = false;
                        //         return false;
                        //     }
                        // }
                        console.log("继续1");
                        // // 继续提交附件
                        // for (let i = 0; i < _that.fileList.length; i++) {
                        //     const file = _that.fileList[i];
                        //     if(!file.raw) { // 是回显时的链接，直接跳过
                        //         _that.activeInfo.pdfList.push({url: file.url, name: file.name});
                        //         continue;
                        //     }
                        //     let tips = true;
                        //     await _that.addFile("2", file, i).then(res => {
                        //         const filePre = file.name.split(".")[0].slice(0, 90);
                        //         const fileName = filePre + "." + file.name.split(".")[1];
                        //         _that.activeInfo.pdfList.push({url: res.url, name: fileName});
                        //     }).catch(err => {
                        //         _that.activeInfo.pdfList = [];
                        //         tips = false;
                        //     });
                        //     if(!tips) {
                        //         _that.loading = false;
                        //         return false;
                        //     }
                        // };
                        console.log("继续2", _that.activeInfo);

                        // let param = {
                        //     ..._that.activeInfo
                        // }
                        // delete param.file;
                        // let url = "/newActivity/add";
                        // let tips = "活动添加成功";
                        // if(_that.pageType === "1") {
                        //     url = "/newActivity/edit";
                        //     param.id = _that.activeId;
                        //     tips = "活动编辑成功";
                        // }
                        // console.log('设置', param);
                        // // return
                        // _that.$request.post(url, param, res => {
                        //     _that.tools.popMessage(tips, 1);
                        //     _that.loading = false;
                        //     _that.$router.back(-1);
                        // }, err => {
                        //     _that.loading = false;
                        // })                       

                        const formData = new FormData()
                        formData.append('title', _that.activeInfo.title)
                        formData.append('startDate', _that.activeInfo.startDate)
                        formData.append('place', _that.activeInfo.place)
                        formData.append('createUser', _that.activeInfo.createUser)
                        formData.append('activityIntro', _that.activeInfo.activityIntro)
                        // formData.append('imgList', _that.activeInfo.imgList)
                        // formData.append('file','')
                        
                        if(_that.activeInfo.imgList.length && !_that.activeInfo.imgList[0].hasOwnProperty('id')){
                            formData.append('imgList', _that.activeInfo.imgList[0].raw)
                        }
                        // formData.append('imgList', _that.activeInfo.imgList[0].raw)

                        if(_that.activeInfo.file.length && !_that.activeInfo.file[0].hasOwnProperty('id')) {
                            formData.append('file', _that.activeInfo.file[0].raw)
                        }

                        let url = "/newActivity/add";
                        let tips = "活动添加成功";
                        console.log('this.pageType', _that.pageType);
                        // console.log('1111', typeof _that.activeInfo.file === 'File');
                        // if(typeof _that.activeInfo.file === 'File'){
                        //     console.log();
                        // }



                        if (_that.pageType == "1") {
                            url = "/newActivity/update";
                            // param.id = _that.activeId;
                            formData.append('id', _that.activeId)
                            tips = "活动编辑成功";
                        }
                        console.log('xxx1查看', formData, _that.activeInfo);
                        // return
                        _that.$request.post(url, formData, res => {
                            _that.tools.popMessage(tips, 1);
                            _that.loading = false;
                            _that.$router.back(-1);
                        }, err => {
                            _that.loading = false;
                        })
                    }




                    // this.loading = true
                    // const formData = new FormData()
                    // formData.append('title',this.activeInfo.title)
                    // formData.append('startDate',this.activeInfo.startDate)
                    // formData.append('placeName',this.activeInfo.placeName)
                    // formData.append('createUser',this.activeInfo.createUser)
                    // formData.append('activityIntro',this.activeInfo.activityIntro)
                    // formData.append('imgList',this.activeInfo.imgList)
                    // formData.append('file',this.activeInfo.file)

                    // let url = "/newActivity/add";
                    // let tips = "活动添加成功";
                    // if(this.pageType === "1") {
                    //     url = "/newActivity/edit";
                    //     // param.id = _that.activeId;
                    //     formData.append('id', this.activeId)
                    //     tips = "活动编辑成功";
                    // }
                    // console.log('xxx1查看', formData, this.activeInfo);
                    // // return
                    // this.$request.post(url, formData, res => {
                    //     this.tools.popMessage(tips, 1);
                    //     this.loading = false;
                    //     this.$router.back(-1);
                    // }, err => {
                    //     this.loading = false;
                    // })

                } else {
                    console.log("error submit!!");
                    return false;
                }
            })
        },


        /* 提交表单 */
        handleSubmit1() {
            this.$refs.activeForm.validate((valid) => {
                if (valid) {
                    this.loading = true
                    const _that = this;
                    uploadImg();
                    async function uploadImg() {
                        // 传图片
                        for (let i = 0; i < _that.imageList.length; i++) {
                            const img = _that.imageList[i];
                            console.log("图片文件：", img);
                            if (!img.raw) { // 是回显时的链接，直接跳过
                                _that.activeInfo.imgList.push({ url: img.url, name: img.name });
                                continue;
                            }
                            let tips = true;
                            await _that.addFile("1", img, i).then(res => {
                                const filePre = img.name.split(".")[0].slice(0, 90);
                                const fileName = filePre + "." + img.name.split(".")[1];
                                _that.activeInfo.imgList.push({ url: res.url, name: fileName });
                            }).catch(err => {
                                _that.activeInfo.imgList = [];
                                tips = false;
                            });
                            if (!tips) {
                                _that.loading = false;
                                return false;
                            }
                        }
                        console.log("继续1");
                        // 继续提交附件
                        for (let i = 0; i < _that.fileList.length; i++) {
                            const file = _that.fileList[i];
                            if (!file.raw) { // 是回显时的链接，直接跳过
                                _that.activeInfo.pdfList.push({ url: file.url, name: file.name });
                                continue;
                            }
                            let tips = true;
                            await _that.addFile("2", file, i).then(res => {
                                const filePre = file.name.split(".")[0].slice(0, 90);
                                const fileName = filePre + "." + file.name.split(".")[1];
                                _that.activeInfo.pdfList.push({ url: res.url, name: fileName });
                            }).catch(err => {
                                _that.activeInfo.pdfList = [];
                                tips = false;
                            });
                            if (!tips) {
                                _that.loading = false;
                                return false;
                            }
                        };
                        console.log("继续2", _that.activeInfo);
                        let param = {
                            ..._that.activeInfo
                        }


                        // const formData = new FormData()
                        // formData.append('title',_that.activeInfo.title)
                        // formData.append('startDate',_that.activeInfo.startDate)
                        // formData.append('placeName',_that.activeInfo.placeName)
                        // formData.append('createUser',_that.activeInfo.createUser)
                        // formData.append('activityIntro',_that.activeInfo.activityIntro)
                        // formData.append('imgList',_that.activeInfo.imgList)
                        // formData.append('file',_that.activeInfo.file)

                        delete param.file;
                        let url = "/newActivity/add";
                        let tips = "活动添加成功";
                        if (_that.pageType === "1") {
                            url = "/newActivity/update";
                            param.id = _that.activeId;
                            tips = "活动编辑成功";
                        }
                        console.log('设置', param);
                        // return
                        _that.$request.post(url, param, res => {
                            _that.tools.popMessage(tips, 1);
                            _that.loading = false;
                            _that.$router.back(-1);
                        }, err => {
                            _that.loading = false;
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            })
        },
        /**
         * 提交图片/文档
         * @param {String} type 接口所需参数：类型 1-图片  2-pdf/文件
         * @param {File} file 接口所需参数：文件
         */
        addFile(type, file, index) {
            const formData = new FormData();
            formData.append("type111", type);
            formData.append("file", file.raw);
            formData.append("fileName", file.name);
            return new Promise((resolve, reject) => {
                this.$request.post("/activity/addFile", formData, res => {
                    resolve(res);
                }, err => {
                    reject(err);
                })
            });
        },
        /* 下载文件 */
        downloadFile(file) {
            // download(file.url, file.name);
            this.tools.downloadUrl("", file.url, file.name);
        }

    }
}
</script>
<style lang="scss" scoped>
.close-box {
    width: 40rem;
    border-radius: 0.5rem;
    border: 0.06rem transparent solid;
    position: relative;
    transition: all 0.5s;

    padding: 0 0.5rem {
        right: 1.5rem;
    }

    ;

    margin: 0.5rem {
        left: 0;
    }

    ;

    &:hover {
        border-color: #666666;
    }

    .remove-i {
        cursor: pointer;
        @include common-absolute($right: 0.5rem, $top: 50%, $middle: -50%)
    }

    .download {
        color: #239CF7;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.limit-max {
    width: 50rem;
}

::v-deep .el-button--primary:focus {
    background: #1C9399;
    border-color: #1C9399;
    color: #FFFFFF;
}
</style>